<template>
  <div class="dqr-page-wrap">
    <CPageTable @register="registerPage" v-model:searchForm="searchForm">
      <template #headerTips>
        <el-row :gutter="12" class="dqr-header" v-if="!isNullOrUnDef(dqr)">
          <el-col :span="6">
            <div class="dqr-header-item">
              <p class="g-font-14n2">碳足迹结果</p>
              <p class="dqr-value">{{ thousandFormat(renderResultUnit(info.accountResult)) }}</p>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="dqr-header-item">
              <p class="g-font-14n2">偏差范围</p>
              <p class="dqr-value">±{{ renderResultUnit(info.deviation) }}</p>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="dqr-header-item">
              <p class="g-font-14n2 g-flex-start-center"
                >不确定度
                <el-tooltip placement="top" content="按95%置信区间计算">
                  <CIcon class="g-ml4 des-icon" type="c-xian-shuoming"></CIcon> </el-tooltip
              ></p>
              <p class="dqr-value">{{ rateFormat(info.uncertainty) }} </p>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="dqr-header-item">
              <p class="g-font-14n2">DQR分值</p>
              <p class="result-item-value" v-if="isNullOrUnDef(dqr)">-</p>
              <div class="g-flex-start-center" v-else>
                <CScopeTag type="text" :scope="dqr"></CScopeTag>
                <span class="dqr-value g-ml8">{{ dqr }}</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </template>
      <template #headerRightButton>
        <el-button text @click="seeRule">
          <CIcon class="g-mr4" type="c-xian-shuoming"></CIcon>
          评分规则</el-button
        >
        <!-- TODO 权限配置 -->
        <el-button
          :loading="discernLoading"
          @click="handleDiscern"
          v-btnPermission="'PCF_MODEL_CREATE'"
        >
          识别最相关
        </el-button>

        <el-button @click="handleBatch" v-btnPermission="'PCF_MODEL_CREATE'"> 批量评分 </el-button>
        <el-button
          type="primary"
          :loading="calcLoading"
          @click="handleCalc"
          v-btnPermission="'PCF_MODEL_CREATE'"
        >
          <CIcon type="c-xian-jisuan" class="g-mr4"></CIcon>
          {{ !isNullOrUnDef(dqr) ? '重新计算' : '立即计算' }}
        </el-button>
      </template>
      <template #lifeCycleStage="{ scope }">
        {{ ProcessStageMap[scope.row.lifeCycleStage as keyof typeof ProcessStageMap] }}
      </template>
      <template #processType="{ scope }">
        {{ DqrTypesListMap[scope.row.processType as keyof typeof DqrTypesListMap] }}
      </template>
      <template #P="{ scope }">
        <div class="dqr-item">
          <span>{{ empty(scope.row.activityDqr?.accuracyDqr) }}</span>
          <el-tooltip content="最相关" placement="top" v-if="scope.row.relevanceFlag">
            <c-icon type="c-xian-xiangguanlian" class="dqr-icon"></c-icon>
          </el-tooltip>
        </div>
      </template>
      <template #TiR="{ scope }">
        {{ empty(scope.row.activityDqr?.timeDqr) }}
      </template>
      <template #TeR="{ scope }">
        {{ empty(scope.row.activityDqr?.techDqr) }}
      </template>
      <template #GeR="{ scope }">
        {{ empty(scope.row.activityDqr?.regionDqr) }}
      </template>
      <template #factorTiR="{ scope }">
        {{ empty(scope.row.factorDqr?.timeDqr) }}
      </template>
      <template #factorTeR="{ scope }">
        {{ empty(scope.row.factorDqr?.techDqr) }}
      </template>
      <template #factorGeR="{ scope }">
        {{ empty(scope.row.factorDqr?.regionDqr) }}
      </template>
      <template #dataSlot="{ scope }">
        <el-popover placement="bottom" :width="300" trigger="hover">
          <template #reference>
            <p class="g-link" @mouseenter="handleNodeClick(scope.row)">{{ scope.row.nodeName }} </p>
          </template>
          <div v-loading="nodeInfoLoading">
            <p class="g-font-12n2"
              ><span class="pop-title">数据名称：</span>
              <span>{{ empty(scope.row.nodeName) }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">所属层级：</span>
              <span>{{ empty(nodeInfo?.nodePath) }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">数据值：</span>
              <span>{{ empty(nodeInfo?.dosage) }}{{ nodeInfo?.unit }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">数据主体：</span>
              <span>{{ empty(nodeInfo?.dataSubject) }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">数据时间：</span>
              <span>{{ empty(nodeInfo?.year) }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">备注：</span>
              <span>{{ empty(nodeInfo?.remark) }}</span>
            </p>
          </div>
        </el-popover>
      </template>
      <template #factor="{ scope }">
        <el-popover placement="bottom" :width="300" trigger="hover" v-if="scope.row.factorName">
          <template #reference>
            <p
              class="g-link g-ell"
              style="width: 100%"
              @mouseenter="handleFactorClick(scope.row)"
              >{{ scope.row.factorName }}</p
            >
          </template>
          <div v-loading="factorInfoLoading">
            <p class="g-font-14n1b">{{ scope.row.name }} </p>
            <p class="g-font-12n2"
              ><span class="pop-title">因子编号：</span>
              <span>{{ empty(factorInfo.factorNo) }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">因子名称：</span>
              <span>{{ empty(factorInfo.factorName) }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">英文名称：</span>
              <span>{{ empty(factorInfo.enName) }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">因子类别：</span>
              <span>{{
                FactorCategoryMap[factorInfo.category as keyof typeof FactorCategoryMap]
              }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">因子值：</span>
              <span>{{ empty(factorInfo.emissionFactor) }} {{ factorInfo.factorUnit }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">因子来源：</span>
              <span>{{
                FactorSourceMap[factorInfo.factorSource as keyof typeof FactorSourceMap] || '-'
              }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">基准年：</span>
              <span>{{ empty(factorInfo.baseYear) }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">因子标签：</span>
              <span>{{ empty(factorInfo.tag) }}</span>
            </p>
            <p class="g-font-12n2"
              ><span class="pop-title">备注：</span>
              <span>{{ empty(factorInfo.comment) }}</span>
            </p>
          </div>
        </el-popover>
        <span v-else>-</span>
      </template>
      <template #op="{ scope }">
        <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" />
      </template>
      <template #batchOperaBtns="{ selection }">
        <el-button
          class="c-btn28"
          @click="handleBatch"
          type="primary"
          :disabled="!(selection.length > 0)"
          >批量评分</el-button
        >
      </template>
    </CPageTable>
  </div>
  <DqrDialog
    v-model:visible="showDqrDialog"
    :rowData="selectRow"
    :nodeNoList="selectIds"
    :model-no="modelNo as string"
    @refresh="handleRefresh"
  ></DqrDialog>
  <DqrDrawer v-model:visible="dqrVisible"></DqrDrawer>
</template>
<script lang="ts">
export default {
  name: 'DQR'
};
</script>
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import { useList } from './useList';
import { empty, rateFormat, thousandFormat, renderResultUnit } from '@/utils/index';
import type { TableButtonItem } from '@/components/CTable';
import { CTableButtonGroup } from '@/components/CTable';
import DqrDialog from './components/DqrDialog/index.vue';
import DqrDrawer from './components/DqrDrawer/index.vue';
import {
  ProcessStageMap,
  DqrTypesListMap,
  FactorCategoryMap,
  FactorSourceMap
} from '@/constants/enum';
import CScopeTag from '@/businessComponents/CScopeTag/index.vue';

import {
  recognizeRelevance,
  calcDqr,
  getNodeInfo,
  getFactorInfo,
  getDqrResult
} from '@/apis/pcf/myModel/dqr';
import { isNullOrUnDef } from '@/utils/is';
import type { IDqrResult } from '@/apis/pcf/myModel/model/modelDqr';
import { useMessage } from '@/hooks/useMessage';
const { searchForm, tableOptions, tableFieldsSetting, modelNo, searchOptions } = useList();
const { createConfirm, createMessage } = useMessage();

const options = reactive<CPageTableProps>({
  title: '数据质量分析(DQR与不确定性)',
  tableOptions,
  tableFieldsSetting,
  searchOptions,
  enableFieldsSetting: true
});
const showDqrDialog = ref(false);
const selectRow = ref();
const selectIds = ref<string[]>([]);
function getTableButtonsConfig(row: any): TableButtonItem[] {
  return [
    {
      text: '评分',
      // TODO:按钮权限
      // btnPermission: 'PCF_MODEL_VIEW',
      onClick: () => goScore('SOLE', row)
    }
  ];
}

const [registerPage, { refresh, getSelection }] = useCPageTable(options);

const discernLoading = ref(false);
const dqr = ref<number | undefined>(undefined);
const info = ref<IDqrResult>({} as IDqrResult);
const getDqr = async () => {
  try {
    const data = await getDqrResult(modelNo as string);
    info.value = data;
    dqr.value = data.dqr;
  } catch (error) {
    console.log('error', error);
  }
};
getDqr();
const handleRefresh = () => {
  refresh();
  dqr.value = undefined;
};
const handleDiscern = async () => {
  // 识别最相关
  try {
    discernLoading.value = true;
    await recognizeRelevance(modelNo as string);
    createMessage.success('识别最相关成功！');
    handleRefresh();
  } finally {
    discernLoading.value = false;
  }
};

const calcLoading = ref(false);
const handleCalc = async () => {
  // 识别最相关
  try {
    calcLoading.value = true;
    const result = await calcDqr(modelNo as string);
    createMessage.success('计算成功！');
    dqr.value = result;

    refresh();
    getDqr();
  } finally {
    calcLoading.value = false;
  }
};

const dqrVisible = ref(false);
const seeRule = () => {
  dqrVisible.value = true;
};
const handleBatch = () => {
  if (getSelection().length > 0) {
    goScore('BATCH');
  } else {
    createMessage.warning('请先选择需要评分的数据');
  }
};
const goScore = (type: 'SOLE' | 'BATCH', row?: any) => {
  // 去评分
  showDqrDialog.value = true;
  if (type == 'SOLE') {
    selectIds.value = [row.nodeNo];
    selectRow.value = row;
  } else {
    const selection = getSelection();
    selectIds.value = selection.map((item: any) => item.nodeNo);
    selectRow.value = selection[0];
  }
};
const nodeInfo = ref<any>({});
const nodeInfoLoading = ref(false);

const handleNodeClick = async (row: any) => {
  try {
    nodeInfoLoading.value = true;
    const data = await getNodeInfo(row.nodeNo);
    nodeInfo.value = data ?? {};
  } finally {
    nodeInfoLoading.value = false;
  }
};

const factorInfo = ref<any>({});
const factorInfoLoading = ref(false);

const handleFactorClick = async (row: any) => {
  try {
    factorInfoLoading.value = true;
    const data = await getFactorInfo(row.factorNo);
    factorInfo.value = data ?? {};
  } finally {
    factorInfoLoading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.dqr-page-wrap {
  margin: 0 0 32px;
  flex: 1;
  display: flex;
  flex-direction: column;
  :deep(.c-page-table__body) {
    height: calc(100vh - 50px - 40px - 56px - 65px);
    overflow-y: auto;
    overflow-x: hidden;
    .c-page-table__body-main {
      height: 100%;
    }
    .body-main__table {
      padding: 0 16px;
      height: 100%;
    }
  }
}
.pop-title {
  display: inline-block;
  width: 78px;
}
.dqr-item {
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;
}
.dqr-icon {
  color: #96a7b3;
  font-size: 16px;
}
.dqr-header {
  padding: 0 20px;
  margin-bottom: 8px;
  .dqr-header-item {
    width: 100%;
    height: 48px;
    background: #f8fbfc;
    border-radius: 3px;
    border: 1px solid #ebeff2;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
  }
  .dqr-value {
    font-size: 16px;
    color: #0a1f33;
    line-height: 28px;
    // font-family: D-DINExp, D-DINExp;
    font-family: D-DIN-Bold;
  }
  .des-icon {
    color: #96a7b3;
    &:hover {
      color: $themeColor;
    }
  }
}
</style>
